import { Component, EventEmitter, Input, OnInit, Output } from '@angular/core';
import {
  FormGroup,
  FormControl,
  Validators,
  FormBuilder,
} from '@angular/forms';

@Component({
  selector: 'app-delete-column',
  templateUrl: './delete-column.component.html',
  styleUrls: ['./delete-column.component.css'],
})
export class DeleteColumnComponent implements OnInit {
  visible = false;

  validateForm!: FormGroup;
  listOfControl: Array<{ id: number; column: string }> = [];

  filterColumn: any;
  @Input() columns: any;
  @Output() result = new EventEmitter();
  open(): void {
    this.validateForm.reset();
    this.visible = true;
  }

  close(): void {
    this.visible = false;
  }
  addField(e?: MouseEvent): void {
    if (e) {
      e.preventDefault();
    }
    const id =
      this.listOfControl.length > 0
        ? this.listOfControl[this.listOfControl.length - 1].id + 1
        : 0;

    const control = {
      id,
      column: `column${id}`,
    };
    const index = this.listOfControl.push(control);
    // console.log(this.listOfControl[this.listOfControl.length - 1]);
    this.validateForm.addControl(
      this.listOfControl[index - 1].column,
      new FormControl(null, [Validators.required])
    );
  }

  removeField(i: { id: number; column: string }, e: MouseEvent): void {
    e.preventDefault();
    if (this.listOfControl.length > 1) {
      const index = this.listOfControl.indexOf(i);
      this.listOfControl.splice(index, 1);
      this.validateForm.removeControl(i.column);
    }
  }

  submitForm(): void {
    if (this.validateForm.valid) {
      let item: { name: string }[] = [];
      this.listOfControl.map((control) => {
        item.push(this.validateForm.controls[control.column].value);
      });
      this.result.emit(item);
      this.close();
    } else {
      Object.values(this.validateForm.controls).forEach((control) => {
        if (control.invalid) {
          control.markAsDirty();
          control.updateValueAndValidity({ onlySelf: true });
        }
      });
    }
  }
  constructor(private fb: FormBuilder) {}

  ngOnInit(): void {
    this.validateForm = this.fb.group({});
    this.addField();
    this.filterColumn = this.columns;
  }
  columnChange(e: any, i: number) {
    Promise.resolve().then(() =>
      this.validateForm.controls[`column${i}`].updateValueAndValidity()
    );

    this.filterColumn = this.columns.filter(
      (c: { name: any }) =>
        !this.listOfControl
          .map((n) => this.validateForm.controls[n.column].value)
          .includes(c.name)
    );
  }
}
